package com.authine.cloudpivot.ext.Utils;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;

/**
    
    *@Author hxd
    
    *@Date  2022/10/9 23:21
    
    *@Description 
     
    **/
 public class FormDataFileUpload {




    public static String fileUpload(File file, int size, String fileName,String suffix, String remarks){

        String token ="6724858270fe01ae420589f772510522585c35e893e29d5e1c84dd83cd15732a18b893";
        String parentId = "2599";

        String uploadUrl = String.format("http://47.104.86.126:188/app/file/upload-file/%s/%s/mobile_sha256/-1/", parentId,token);

        RestTemplate restTemplate = new RestTemplate();

        // 必须设置文件类型的请求头,同时有其他属性值需要加在请求体里面,而不是请求参数,因为是post请求
        String uri = uploadUrl;

        FileSystemResource fileSystemResource = new FileSystemResource(file);

        HttpHeaders headers = new HttpHeaders();

        headers.add("content-type", "multipart/form-data");//设置请求头类型

        MultiValueMap map = new LinkedMultiValueMap();

        map.add("file", fileSystemResource);//设置请求头属性

        map.add("fileName", fileName.concat(suffix));
        map.add("remarks", remarks);// 档案代码主体部分
        map.add("size", size);

        HttpEntity http = new HttpEntity(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(uri, http, String.class);

        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }else {
            return String.valueOf(responseEntity.getStatusCodeValue());
        }

    }
}
